<template>
	<view class="profile-page">
		<!-- 未登录状态 -->
		<view class="unlogin-container" v-if="username.length==0">
			<view class="login-card">
				<!-- 头像区域 -->
				<view class="avatar-container">
					<view class="avatar-icon">
						<uni-icons type="person-filled" size="50" color="#4CAF50"></uni-icons>
					</view>
				</view>

				<!-- 提示文字 -->
				<text class="login-tip">您还未登录，请先登录</text>

				<!-- 登录按钮 -->
				<button class="login-btn" @click="handleLogin">立即登录</button>

				<!-- 其他登录方式 -->
				<view class="other-login">
					<text class="divider">或通过以下方式登录</text>
					<view class="third-party">
						<button class="third-btn wechat" open-type="getUserInfo" @getuserinfo="onGetUserInfo">
							<uni-icons type="weixin" size="24" color="#fff"></uni-icons>
						</button>
					</view>
				</view>
			</view>
		</view>


		<!-- 已登录状态 -->
		<block v-else>
			<!-- 用户信息区 -->
			<view class="user-info">
				<view class="avatar-container">
					<image class="avatar" :src="avatarUrl" mode="aspectFill" @click="handleAvatarClick" />
					<uni-icons type="camera-filled" size="20" color="#fff" class="camera-icon"
						@click="handleChooseAvatar" />
				</view>
				<view class="user-detail">
					<text class="nickname">{{ username }}</text>
					<view class="phone-container">
						<text class="phone">tel:{{ phone }}</text>
						<!-- <uni-icons type="compose" size="16" color="#666" @click="handleEditPhone" /> -->
					</view>
				</view>
			</view>

			<!-- 功能模块列表 -->
			<view class="function-list">
				<!-- 第一组 -->
				<!-- <view class="function-group">
					<view class="function-item" v-for="item in coreFunctions" :key="item.id"
						@click="handleFunctionClick(item.path)">
						<uni-icons :type="item.icon" size="20" color="#4CAF50" class="function-icon" />
						<text class="function-name">{{ item.name }}</text>
						<uni-icons type="arrowright" size="16" color="#999" class="arrow-icon" />
					</view>
				</view> -->

				<!-- 第二组 -->
				<view class="function-group">
					<view class="function-item" v-for="item in appFunctions" :key="item.id"
						@click="handleFunctionClick(item.path)">
						<uni-icons :type="item.icon" size="20" color="#4CAF50" class="function-icon" />
						<text class="function-name">{{ item.name }}</text>
						<view class="right-content">
							<text class="badge" v-if="item.id === 'message' && messageCount > 0">
								{{ messageCount }}
							</text>
							<uni-icons type="arrowright" size="16" color="#999" class="arrow-icon" />
						</view>
					</view>
				</view>
			</view>

			<!-- 退出按钮 -->
			<view class="logout-container">
				<button class="logout-btn" @click="handleLogout">退出登录</button>
			</view>
		</block>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';

	// 用户信息
	const username = ref('');
	const phone = ref('');
	const avatarUrl = ref('/static/images/user.jpg');
	const isLogin = ref(false);
	const messageCount = ref(0);



	// 页面显示时更新消息数量
	onShow(() => {
		updateMessageCount();
	});

	// 更新未读消息数量
	const updateMessageCount = () => {
		uni.request({
			url: 'http://localhost:3000/messages?read=false',
			method: 'GET',
			success: (res) => {
				// 获取未读消息数量
				messageCount.value = res.data.length;
			},
			fail: (err) => {
				console.error('获取未读消息数量失败:', err);
				messageCount.value = 0;
			}
		});
	};




	// 功能列表
	const appFunctions = ref([{
			id: 'message',
			name: '消息通知',
			icon: 'chat',
			path: '/pages/message/message'
		},
		{
			id: 'setting',
			name: '设置',
			icon: 'gear',
			path: '/pages/settings/settings'
		},
		{
			id: 'help',
			name: '帮助与反馈',
			icon: 'help',
			path: ''
		},
		{
			id: 'about',
			name: '关于农田小管家',
			icon: 'info',
			path: ''
		},
	]);

	// 页面加载时检查登录状态
	onLoad(() => {
		checkLoginStatus();
	});

	// // 页面显示时更新消息数量
	// onShow(() => {
	// 	updateMessageCount();
	// });

	// 检查登录状态
	const checkLoginStatus = () => {
		const userinfo = window.sessionStorage.getItem('userinfo');
		if (userinfo) {
			try {
				const userData = JSON.parse(userinfo);
				username.value = userData.username || '';
				phone.value = userData.phone || '';
				isLogin.value = true;

				// 如果有头像信息也更新
				if (userData.avatar) {
					avatarUrl.value = userData.avatar;
				}
			} catch (e) {
				console.error('解析用户信息失败:', e);
				clearUserData();
			}
		} else {
			clearUserData();
		}
	};

	// // 更新消息数量
	// const updateMessageCount = () => {
	// 	// 这里可以替换为实际的获取消息数量的逻辑
	// 	messageCount.value = Math.floor(Math.random() * 5);
	// };

	// 登录方法
	const handleLogin = () => {
		uni.navigateTo({
			url: '/pages/login/login'
		});
	};

	// 处理微信登录
	const onGetUserInfo = (e) => {
		console.log('微信用户信息:', e.detail);
		// 这里可以添加微信登录的逻辑
	};

	// 选择头像
	const handleChooseAvatar = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				if (res.tempFilePaths.length > 0) {
					avatarUrl.value = res.tempFilePaths[0];
					// 可以在这里保存头像到服务器或本地存储
					saveAvatarToStorage(res.tempFilePaths[0]);
					uni.showToast({
						title: '头像更换成功',
						icon: 'success'
					});
				}
			},
			fail: (err) => {
				console.error('选择图片失败:', err);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				});
			}
		});
	};

	// 保存头像到存储
	const saveAvatarToStorage = (avatarPath) => {
		const userinfo = window.sessionStorage.getItem('userinfo');
		if (userinfo) {
			try {
				const userData = JSON.parse(userinfo);
				userData.avatar = avatarPath;
				window.sessionStorage.setItem('userinfo', JSON.stringify(userData));
			} catch (e) {
				console.error('保存头像失败:', e);
			}
		}
	};

	// 点击头像
	const handleAvatarClick = () => {
		uni.showActionSheet({
			itemList: ['更换头像', '查看头像'],
			success: (res) => {
				if (res.tapIndex === 0) {
					handleChooseAvatar();
				} else if (res.tapIndex === 1) {
					uni.previewImage({
						urls: [avatarUrl.value]
					});
				}
			}
		});
	};

	// 点击功能项
	const handleFunctionClick = (path) => {
		if (path) {
			uni.navigateTo({
				url: path
			});
		}
	};

	// 清除用户数据
	const clearUserData = () => {
		username.value = '';
		phone.value = '';
		avatarUrl.value = '/static/images/user.jpg';
		isLogin.value = false;
	};

	// 退出登录
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					// 清除所有session数据
					window.sessionStorage.removeItem('userinfo');

					// 重置用户数据
					clearUserData();

					// 显示退出成功提示
					uni.showToast({
						title: '已退出登录',
						icon: 'success'
					});
				}
			}
		});
	};
</script>
<style>
	page {
		height: 100%;
		background-color: #f5f5f5;
	}

	.profile-page {
		display: flex;
		flex-direction: column;
		height: 100%;
	}


	/* 未登录容器 */
	.unlogin-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		background-color: #f5f5f5;
		padding: 20px;
	}

	/* 登录卡片 */
	.login-card {
		width: 100%;
		max-width: 400px;
		background: #fff;
		border-radius: 12px;
		padding: 30px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
		text-align: center;
		box-sizing: border-box;
	}

	/* 头像图标 */
	.avatar-container {
		margin-bottom: 20px;
	}

	.avatar-icon {
		width: 80px;
		height: 80px;
		line-height: 80px;
		text-align: center;
		background-color: #e8f5e9;
		border-radius: 50%;
		display: block;
		margin: 0px 120px;


	}

	/* 提示文字 */
	.login-tip {
		font-size: 16px;
		color: #666;
		margin-bottom: 30px;
		display: block;
	}

	/* 登录按钮 */
	.login-btn {
		background-color: #4CAF50;
		color: #fff;
		height: 44px;
		line-height: 44px;
		border-radius: 22px;
		font-size: 16px;
		margin-bottom: 20px;
	}

	.login-btn::after {
		border: none;
	}

	/* 其他登录方式 */
	.divider {
		color: #999;
		font-size: 14px;
		position: relative;
		display: block;
		margin: 20px 0;
	}

	.divider::before,
	.divider::after {
		content: "";
		position: absolute;
		top: 50%;
		width: 30%;
		height: 1px;
		background-color: #eee;
	}

	.divider::before {
		left: 0;
	}

	.divider::after {
		right: 0;
	}

	/* 第三方登录按钮 */
	.third-btn {
		width: 50px;
		height: 50px;
		border-radius: 50%;
		padding: 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.third-btn::after {
		border: none;
	}

	.wechat {
		background-color: #07C160;
	}

	/* 已登录状态原有样式保持不变 */
	.user-info {
		height: 250rpx;
		background: linear-gradient(135deg, #4CAF50, #8BC34A);
		padding: 40rpx 30rpx;
		display: flex;
		align-items: center;
		color: #fff;
	}

	.avatar-container {
		position: relative;
		width: 120rpx;
		height: 120rpx;
		margin-right: 30rpx;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		border: 4rpx solid rgba(255, 255, 255, 0.3);
	}

	.camera-icon {
		position: absolute;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 50%;
		padding: 6rpx;
	}

	.user-detail {
		flex: 1;
	}

	.nickname {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
	}

	.phone-container {
		display: flex;
		align-items: center;
	}

	.phone {
		font-size: 28rpx;
		margin-right: 10rpx;
	}

	/* 功能模块列表 */
	.function-list {
		flex: 1;
		padding: 20rpx 0;
		background-color: #fff;
	}

	.function-group {
		margin-bottom: 20rpx;
	}

	.function-item {
		height: 100rpx;
		padding: 0 30rpx;
		display: flex;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.function-icon {
		margin-right: 20rpx;
	}

	.function-name {
		flex: 1;
		font-size: 30rpx;
		color: #333;
	}

	.right-content {
		display: flex;
		align-items: center;
	}

	.badge {
		background-color: #FF5722;
		color: #fff;
		font-size: 20rpx;
		min-width: 36rpx;
		height: 36rpx;
		line-height: 36rpx;
		text-align: center;
		border-radius: 18rpx;
		padding: 0 10rpx;
		margin-right: 20rpx;
	}

	.arrow-icon {
		opacity: 0.5;
	}

	/* 退出按钮 */
	.logout-container {
		padding: 40rpx 30rpx;
		background-color: #fff;
	}

	.logout-btn {
		background-color: #FF5722;
		color: #fff;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		font-size: 32rpx;
		margin: 0;
	}

	.logout-btn::after {
		border: none;
	}
</style>